/**
 * The simple cross-browser JavaScript profiler.
 *
 * core.util.beginProfile('Doing stuff');
 * // do stuff
 * core.util.endProfile('Doing stuff');
 * // The output will be like the following:
 * // 23:36:2.312 [Doing stuff] 31 ms 
 *
 * @author Andrey Anisimov <hercules@inbox.ru>
 */
 
class Profiler {

	this.Profiler = function() {
		this.profilers = {};
	}

	/**
	 * Starts profiler for specified name.
	 *
	 * @param name (string) The name of the profiler.
	 */
	this.beginProfile = function(name) {
		this.profilers[name] = new Date().getTime();
	}

	/**
	 * Stops profiler and prints the profiling result.
	 *
	 * @param name (string) The name of the profiler.
	 */
	this.endProfile = function(name) {
		var now = new Date();
		var diff = now.getTime() - this.profilers[name];
		this.trace((now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + ' [' + name + '] ' + diff + ' ms<br />'));
	}

	/**
	 * Returns the document element to use for displaying info.
	 *
	 * @return HtmlElement
	 */
	this.getProfileElement = function() {
		if (!this.element) {
			this.element = document.createElement('div');
			this.element.style.position = 'absolute';
			this.element.style.left = '0px';
			this.element.style.bottom = '0px';
			this.element.style.width = '100%';
			this.element.style.height = '200px';
			this.element.style.border = '1px solid blue';
			this.element.style.overflowY = 'scroll';
			this.element.style.backgroundColor = '#ffffff';
			document.body.appendChild(this.element);
		}
		return this.element;
	}

	/**
	 * Prints out the line of text.
	 *
	 * @param text (string) The text to trace.
	 */
	this.trace = function(text) {
		var element = this.getProfileElement();
		element.innerHTML += text;
		element.scrollTop = element.scrollHeight;
	}
}

/**
 * Returns the singleton profiler instance.
 *
 * @return Profiler
 */
Profiler.getInstance = function() {
	if (!this.instance) {
		this.instance = new Profiler();
	}
	return this.instance;
}

/**
 * Starts profiling.
 *
 * @param name (string) The name of the current profiler.
 */
core.util.beginProfile =
Profiler.beginProfile = function(name) {
	Profiler.getInstance().beginProfile(name);
}

/**
 * Stops profiling.
 *
 * @param name (string) The name of the current profiler.
 */
core.util.endProfile =
Profiler.endProfile = function(name) {
	Profiler.getInstance().endProfile(name);
}